//
//  HMainWC.m
//  HMusicPlayer
//
//  Created by Hament on 14/9/15.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HMainWC.h"
#import "GRCustomizableWindow.h"
#import "HCoreConfig.h"
#import "HskinManager.h"
#import "HView.h"
#import "HPlayListView.h"
#import "HSongListView.h"
#import "HPlayPlaneView.h"
#import "HSearchHeaderView.h"
#import "HGlobalReminder.h"
#import "HGroupListView.h"
#import "HPlaylistItem.h"
#import "HLrcView.h"
#import "HSampleSkinDesignerWC.h"//临时
#import "HTriangleView.h"
#import "HMusicSlider.h"
#import "HSQLManager.h"
#import "HSettingWC.h"
#import "HSongItem.h"
#import "HPlaylistItem.h"
#import "HMainDownloader.h"

#import <OrigamiEngine/ORGMEngine.h>
#import "DOUAudioStreamer.h"
#import "HJAudioPlayer.h"
#import "TagReader.h"
#import "ID3Tag.h"
#import "ID3TagParser.h"
#import "iTunes.h"
#import <AVFoundation/AVFoundation.h>
@interface HMainWC ()<NSWindowDelegate,NSDrawerDelegate>

@property (nonatomic,strong) NSArray * skinList;

@end

@implementation HMainWC


static HMainWC * mainWc=nil;



+(HMainWC*)shareWc{

    @synchronized(self) {
        if (mainWc==nil) {
             mainWc=[[HMainWC alloc] initWithWindowNibName:@"HMainWC"];
             mainWc.skinList=[NSArray arrayWithContentsOfFile:fileBundlePath(@"skinlist", @"plist")];

        }
    }
    return mainWc;

}


- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        // Initialization code here.
        
        
    }
    return self;
}


#pragma mark ----lazyloading-----
-(GRCustomizableWindow*)grwindow{
    
    if (!_grwindow) {
        _grwindow=(GRCustomizableWindow *)[super window];
        //[_grwindow addSettbutton];
    }
    
    return _grwindow;
}

//全局覆盖层
-(HView*)coverView {
    
    if (!_coverView) {
        _coverView=[[HView alloc] initWithFrame:self.rootContentView.bounds];
        _coverView.fillBackGround=^(NSRect dirtyRect){
            CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
            [[NSColor colorWithCalibratedWhite:0.4 alpha:0.5] setFill];
            CGContextFillRect(context, NSRectToCGRect(dirtyRect));
            
        };
        [_coverView setAutoresizingMask:(NSViewMinYMargin|NSViewMaxYMargin|NSViewMaxXMargin|NSViewMinXMargin|NSViewHeightSizable|NSViewWidthSizable)];
    }
    
    return _coverView;
}


-(NSMenu*)importMenu {

    if (!_importMenu) {
        _importMenu=[[NSMenu alloc] init];
        
        NSMenuItem * t1=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"import to itunes", nil) action:@selector(importToitunes) keyEquivalent:@""];
        t1.tag=importItunesTag;
        [_importMenu addItem:t1];
        
        NSMenuItem * t2=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"import as a new playlist", nil) action:@selector(importAsnewplist) keyEquivalent:@""];
        t2.tag=importASPlistTag;
        [_importMenu addItem:t2];
        
        
        NSMenuItem * t3=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"import to playlist", nil) action:nil keyEquivalent:@""];//有子项
        t3.tag=importPlistTag;
        [_importMenu addItem:t3];

        
    }

    return _importMenu;
}

-(NSMenu*)sortMenu {
    
    if (!_sortMenu) {
        _sortMenu=[[NSMenu alloc] init];
        
        
        
        NSMenuItem * t1=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"by name", nil) action:@selector(sortSelect:) keyEquivalent:@""];
        t1.state=NSOffState;
        t1.tag=sortNameTag;
        [_sortMenu addItem:t1];
        
        //默认按日期
        NSMenuItem * t2=[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"by import date", nil) action:@selector(sortSelect:) keyEquivalent:@""];
        t2.state=NSOnState;
        t2.tag=sortDateTag;
        [_sortMenu addItem:t2];
        
    }
    
    return _sortMenu;
}

-(NSMenu*)storeMenu {
    
    if (!_storeMenu) {
        _storeMenu=[[NSMenu alloc] init];
        [_storeMenu addItemWithTitle:@"皮肤制作" action:@selector(skinmake) keyEquivalent:@""];
        
    }
    
    return _storeMenu;
}


-(NSMenu*)skinMenu {
    
    if (!_skinMenu) {
        _skinMenu=[[NSMenu alloc] init];
        //[_skinMenu addItemWithTitle:@"皮肤设计器" action:@selector(skinmake) keyEquivalent:@""];
        
        int i=0;
        for (NSDictionary * dic in self.skinList) {
            NSString *lang=[[HCoreConfig shareConfig] getUserLang];
            NSString * uid=dic[@"uid"];
            
            
            
            //如果是中文,显示中文
            NSString * displayname=([lang isEqualToString:@"zh-Hans"] || [lang isEqualToString:@"zh-Hant"])?dic[@"displayName_zhs"]:dic[@"displayName_en"];
            
            NSMenuItem * t1=[[NSMenuItem alloc] initWithTitle:displayname action:@selector(skinSelect:) keyEquivalent:@""];
            t1.state= ([uid isEqualToString:[HCoreConfig shareConfig].currentSkinManager.uid])?NSOnState: NSOffState ;
            t1.tag=i;
            [_skinMenu addItem:t1];
            i++;
            
        }
        
        
    }
    
    return _skinMenu;
}



-(NSDrawer*)lyricDrawer{

    if (!_lyricDrawer) {
        NSSize contentSize = NSMakeSize(280, 400);
        NSSize mincontentSize = NSMakeSize(280, 400);
        NSSize maxcontentSize = NSMakeSize(300, 2000);
        _lyricDrawer = [[NSDrawer alloc] initWithContentSize:contentSize preferredEdge:NSMinYEdge];
        [_lyricDrawer setParentWindow:self.window];
        [_lyricDrawer setMinContentSize:mincontentSize];
        [_lyricDrawer setMaxContentSize:maxcontentSize];
        //[_lyricDrawer setContentView:self.lyricView];
//        [_lyricDrawer setLeadingOffset:130];
//        [_lyricDrawer setTrailingOffset:0];
        _lyricDrawer.delegate=self;
        
    }

    return _lyricDrawer;
}



#pragma mark ----self callback-----



- (void)windowDidLoad
{
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
    
    //初始化音频引擎
    [HJAudioPlayer sharePlayer].delegate=self;
    
    
    //音量
    NSNumber * volume=[HJAudioPlayer sharePlayer].volume;
    [self.soundSlider setFloatValue:volume.floatValue];
    self.soundSlider.useScrollWheel=YES;
    
    //全局加载提醒条初始化
    NSRect bounds=self.rootContentView.frame;
    self.loadingReminder=[[HGlobalReminder alloc] initWithFrame:NSMakeRect((bounds.size.width-HReminderWidth)/2, (bounds.size.height-HReminderHeigh)/2, HReminderWidth, HReminderHeigh) remindTx:nil type:0];
    [self.loadingReminder setAutoresizingMask:(NSViewMinYMargin|NSViewMaxYMargin|NSViewMaxXMargin|NSViewMinXMargin)];
    
    //成功处理的reminder
    self.successReminder=[[HGlobalReminder alloc] initWithFrame:NSMakeRect((bounds.size.width-HReminderWidth)/2, (bounds.size.height-HReminderHeigh)/2, HReminderWidth, HReminderHeigh) remindTx:nil type:1];
    [self.successReminder setAutoresizingMask:(NSViewMinYMargin|NSViewMaxYMargin|NSViewMaxXMargin|NSViewMinXMargin)];
   
    
    //失败提示的reminder
    self.failReminder=[[HGlobalReminder alloc] initWithFrame:NSMakeRect((bounds.size.width-HReminderWidth)/2, (bounds.size.height-HReminderHeigh)/2, HReminderWidth, HReminderHeigh) remindTx:nil type:2];
    [self.failReminder setAutoresizingMask:(NSViewMinYMargin|NSViewMaxYMargin|NSViewMaxXMargin|NSViewMinXMargin)];
    
    //进度条
    [self.durationSlider SetisForDuration:YES]; //tracking的时候阻止timer
    
    /*
     Buttons triggering the Sharing Service Picker should be invoked on mouse down, not mouse up.
     */
    [self.shareBtn sendActionOn:NSLeftMouseDownMask];
    [self.sikinBtn sendActionOn:NSLeftMouseDownMask];
    
    //刷新皮肤
    [self refreshSkin];
    
    //[[HCoreConfig shareConfig] getItunesFavouriteSongs];
    
    //[self.window setb]
    
    
    //进度条刷新
    self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                         target:self
                                                       selector:@selector(refreshDurationUI)
                                                       userInfo:nil
                                                        repeats:YES];
    
    
    

    
    
}


#pragma mark ----业务逻辑-----


#pragma mark  --弹出/回收 歌词窗口

-(void)toggleLyricDrawer:(id)sender{

    NSDrawerState state = [self.lyricDrawer state];
    if (NSDrawerOpeningState == state || NSDrawerOpenState == state) {
        [self.lyricDrawer  close];
    } else {
        [self.lyricDrawer  openOnEdge:NSMaxXEdge];
    }

}



#pragma mark 刷新函数
-(void)refreshSkin{

    
    //--------开始根据使用的皮肤配置颜色---------
    //1.标题栏与窗口
    self.grwindow.enableGradients=NO;
    self.grwindow.titlebarHeight = @hwindowHeigh;
    self.window.title=NSLocalizedString(@"Glad Music", nil);
    self.grwindow.titleColor=[HCoreConfig shareConfig].currentSkinManager.titleBarTextColor;
    self.grwindow.titlebarColor=[HCoreConfig shareConfig].currentSkinManager.titleBarBGColor;
    self.grwindow.backgroundColor=[HCoreConfig shareConfig].currentSkinManager.mainPlaneBgColor;

    
    
    //2.playplane color
    self.playplaneView.fillBackGround=^(NSRect dirtyRect){
        CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
        [[HCoreConfig shareConfig].currentSkinManager.mainPlaneBgColor setFill];
        CGContextFillRect(context, NSRectToCGRect(dirtyRect));
        
    };
    
    
    //lyric
    self.lyricView.fillBackGround=^(NSRect dirtyRect){
        CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
        [[HCoreConfig shareConfig].currentSkinManager.mainPlaneBgColor setFill];
        CGContextFillRect(context, NSRectToCGRect(dirtyRect));
        
    };
    
    
    //song title & duration title
    self.songTitleLab.textColor=[HCoreConfig shareConfig].currentSkinManager.songTitleColor;
    self.songDurationLab.textColor=[HCoreConfig shareConfig].currentSkinManager.songTitleColor;
    self.currentDurationLab.textColor=[HCoreConfig shareConfig].currentSkinManager.songTitleColor;
    
    //search header
    self.searchHeaderView.fillBackGround=^(NSRect dirtyRect){
        CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
        [[HCoreConfig shareConfig].currentSkinManager.headerViewBGColor setFill];
        CGContextFillRect(context, NSRectToCGRect(dirtyRect));
        
    };
    
    //menu
    NSColor * menuNc=[HCoreConfig shareConfig].currentSkinManager.headerMenuTextColor;
    NSColor * menuHc=[HCoreConfig shareConfig].currentSkinManager.headerMenuHighlightTextColor;
//    NSShadow * shadow_m=[[NSShadow alloc] init];
//    [shadow_m setShadowColor:[NSColor blackColor]];
//    [shadow_m setShadowOffset:NSMakeSize(1, 1)];
    
    [HCoreConfig configButton:self.importBtn Title:NSLocalizedString(@"Import", nil) normalColor:menuNc helightedColor:menuHc shadow:nil];
    [HCoreConfig configButton:self.sortBtn Title:NSLocalizedString(@"Sort", nil) normalColor:menuNc helightedColor:menuHc shadow:nil];
    [HCoreConfig configButton:self.sikinBtn Title:NSLocalizedString(@"Skin", nil) normalColor:menuNc helightedColor:menuHc shadow:nil];
    [HCoreConfig configButton:self.storeBtn Title:NSLocalizedString(@"Store", nil) normalColor:menuNc helightedColor:menuHc shadow:nil];
    [HCoreConfig configButton:self.settingBtn Title:NSLocalizedString(@"Setting", nil) normalColor:menuNc helightedColor:menuHc shadow:nil];
    [HCoreConfig configButton:self.searchBtn Title:NSLocalizedString(@"Search", nil) normalColor:menuNc helightedColor:menuHc shadow:nil];
    
    //play list ,底色跟普通cell同色
    self.playListView.fillBackGround=^(NSRect dirtyRect){
        CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
        [[HCoreConfig shareConfig].currentSkinManager.leftListNormalCellBGColor setFill];
        CGContextFillRect(context, NSRectToCGRect(dirtyRect));
        
    };
    
    


    
    
    //song list,底色跟普通cell同色
    self.songListView.fillBackGround=^(NSRect dirtyRect){
        CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
        [[HCoreConfig shareConfig].currentSkinManager.rightListCellBGColor1 setFill];
        CGContextFillRect(context, NSRectToCGRect(dirtyRect));
        
    };
    
    
    //歌词提示
    self.lyricView.remindLab.textColor=[HCoreConfig shareConfig].currentSkinManager.lyrcisNormalColor;
    
    //还有一些根据颜色配置的icon
    //--------刷新图片---------
    
    [[HCoreConfig shareConfig] refreshSkinImage];//全局使用的
    

    //
    [self.importBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_newsong_nml"]];
    [self.importBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_newsong_hlt"]];
    
    [self.sortBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_sequence_nml"]];
    [self.sortBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_sequence_hlt"]];
    
    [self.sikinBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_theme_nml"]];
    [self.sikinBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_theme_hlt"]];
    
    [self.storeBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_store_nml"]];
    [self.storeBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_store_hlt"]];

    [self.settingBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_setting_nml"]];
    [self.settingBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_setting_hlt"]];
    
    [self.searchBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_search_nml"]];
    [self.searchBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_search_hlt"]];
    
    [self.preButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pre_nml"]];
    [self.preButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pre_hlt"]];
    
    [self.nextButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_next_nml"]];
    [self.nextButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_next_hlt"]];
    
    [self configThePlayButtonImg];//根据播放状态设置按钮
    
    [self.soundIneraseBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_volume_increase_nml"]];//增加sound
    [self.soundIneraseBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_volume_increase_hlt"]];//减少sound
    
    [self.soundDecreaseBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_volume_decrease_nml"]];//减少sound
    [self.soundDecreaseBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_volume_decrease_hlt"]];//减少sound
    
    
    
    [self.shareBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_share_nml"]];
    [self.shareBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_share_hlt"]];
    
    /* 10.10私有api发生改变,不能添加subview到 themeview
    //窗口setting按钮
    NSButton * settingBtn=[self.grwindow getSettbutton];
    [settingBtn setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_setting_nml"]];
    [settingBtn setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_setting_hlt"]];
     */
//    
    
    [self.playModeButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_mode_cycle_nml"]];//播放模式,判断 ,icon_mode_cycle_nml,icon_mode_list_nml,icon_mode_random_nml
    [self configPlayModeImage];
    
    
    [self.islikeButton setImage:[HCoreConfig shareConfig].unlikeSongImg];//like 或unlike,判断
    [self.islikeButton setAlternateImage:[HCoreConfig shareConfig].likeSongImg];
  
    //--------刷新列表---------
    [self.playListView.tableV reloadData];
    [self.songListView changeIconInAllCell];
    [self.songListView.tableV reloadData];
    [self.lyricView.tableV reloadData];
    
    
}


- (IBAction)imageChange:(NSImageView *)sender {
    
    debugLog(@"imgChange");
}



#pragma mark 刷新播放时间,进度条
- (void)refreshDurationUI {
    
    
if ([HJAudioPlayer sharePlayer].currentUsePlayerType==ORGMEngineType) {
        
   
    if ([HJAudioPlayer sharePlayer].orgmenginePlayer.currentState == ORGMEngineStatePlaying) {
        //更新时间,进度条
        float trackTime=[HJAudioPlayer sharePlayer].orgmenginePlayer.trackTime;
        float playTime=[HJAudioPlayer sharePlayer].orgmenginePlayer.amountPlayed;
        self.currentDurationLab.stringValue=[HCoreConfig convertMileSecond:playTime*1000];
        [self.durationSlider setFloatValue:playTime/trackTime];
        
        [self.lyricView locateHighlightRowWithduration:playTime*1000];

    }
        
} else if ([HJAudioPlayer sharePlayer].currentUsePlayerType==DOUAudioType){

      if ([[HJAudioPlayer sharePlayer].streamPlayerer status]==DOUAudioStreamerPlaying) {
        
          DOUAudioStreamer * _streamer=[HJAudioPlayer sharePlayer].streamPlayerer;
          
          if ([_streamer  duration] == 0.0) {
              [self.durationSlider setFloatValue:0.0f];
              self.currentDurationLab.stringValue=@"0:00";
          }
          else {
              float playTime=[_streamer currentTime];
              self.currentDurationLab.stringValue=[HCoreConfig convertMileSecond:playTime*1000];
              
              [self.durationSlider setFloatValue:playTime/ [_streamer duration]];
              
              [self.lyricView locateHighlightRowWithduration:playTime*1000];
          }

      }

    }
}



//改变时间
-(void)changeCurrentTimeWithDurationSliderFloatValue:(float)durationF {


    if([HJAudioPlayer sharePlayer].currentPlaySongItem) {

        NSUInteger durationTime=[HJAudioPlayer sharePlayer].currentPlaySongItem.songDuration*durationF;
         self.currentDurationLab.stringValue=[HCoreConfig convertMileSecond:durationTime];
        

    }

}



#pragma mark  close 前保存信息
-(void)saveLastplayInfoSetting{

    NSString * path=[HJAudioPlayer sharePlayer].currentPlaySongItem.localPath;//暂时不用
    
     NSDictionary *  dic=@{HVolume:[HJAudioPlayer sharePlayer].volume, // 0~1.0
              HPlayMode:[NSNumber numberWithInteger:[HJAudioPlayer sharePlayer].currentPlayMode],
              HPlaylistID:[HJAudioPlayer sharePlayer].playListID,
              HPlaySongPath:CHECKSTR(path)};//path暂时用不上
   
    [[NSUserDefaults standardUserDefaults] setObject:dic forKey:HCurrentPlayInfo];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark reset playplane ui
-(void)resetPlayplaneUIWithSongItem:(HSongItem*)songitem{

    
    
    //进度条归0
    [self.durationSlider setFloatValue:0.0];
    //时间
    self.currentDurationLab.stringValue=@"0:00";
    

    
    if (songitem) {
    self.songDurationLab.stringValue=[HCoreConfig convertMileSecond:songitem.songDuration];
    //标题和插图
    [self resetPlaneTitleAndImg:songitem];
    
    
    //歌词
        [self.lyricView cleanLyrics];//先清空一次歌词
        [self loadLyricsWithSongItem:songitem];
   
        
    //like
        self.islikeButton.state=songitem.islike;
        
    } else {
    
    self.songDurationLab.stringValue=@"0:00";
      //标题
      self.songTitleLab.stringValue=@"";
      //插图
      self.albumArtImgView.image=[[NSImage alloc] initWithContentsOfFile:fileBundlePath(@"img_defaultAlbum", @"tiff")];
      //清空歌词
        [self.lyricView cleanLyrics];
        //like
        self.islikeButton.state=NSOffState;
    }
    
}


-(void)resetUIWithSongItemChange:(HSongItem * )songitem{

    [HJAudioPlayer sharePlayer].currentPlaySongItem=songitem;
    [self resetPlayplaneUIWithSongItem:songitem];
    
    HPlaylistItem * pitem=[[HMainWC shareWc].playListView getCurrentSelectPlaylistItem];
    //如果当前播放的列表定位 与选中的一致,刷新列表
    if ([pitem.syncid isEqualToString:songitem.playListSyncID]) {
        [self.songListView.tableV reloadData];
    }


}

#pragma mark 只改变标题和插图,用于tab发生改变,或itunes rename
-(void)resetPlaneTitleAndImg:(HSongItem*)songitem{

    @autoreleasepool {
    //标题
    self.songTitleLab.stringValue=songitem.songName;
    
    //插图
    TagReader * tagreader=[[TagReader alloc] initWithFileAtPath:songitem.localPath];
    NSData * albumData=tagreader.albumArt;
    if (albumData) {
        NSImage * img=[[NSImage alloc] initWithData:albumData];
        self.albumArtImgView.image=img;
    }
    //默认图
    else {
        
        

        
        NSString * ext=songitem.localPath.pathExtension.lowercaseString;
        if ([ext isEqualToString:@"aac"] || [ext isEqualToString:@"m4a"] || [ext isEqualToString:@"m4"]) {
            
            [HCoreConfig getSoundPropertyWithPath:songitem.localPath completion:^(NSDictionary * dic){
                NSImage * aimg=dic[HArtwork];
                dispatch_async(dispatch_get_main_queue(), ^{
                
                    if (aimg) {
                        self.albumArtImgView.image=aimg;
                    } else {
                        self.albumArtImgView.image=[[NSImage alloc] initWithContentsOfFile:fileBundlePath(@"img_defaultAlbum", @"tiff")];
                    }
                });

            }];
            
        } else {
                self.albumArtImgView.image=[[NSImage alloc] initWithContentsOfFile:fileBundlePath(@"img_defaultAlbum", @"tiff")];
        
        }
        
        
    
        //debugLog(@"W:%f",self.albumArtImgView.image.size.width);
    
    }

        
 }

}



#pragma mark 加载歌词,调用该方法前应先清空一下歌词
-(void)loadLyricsWithSongItem:(HSongItem*)songitem{

    if (!songitem) {
        return;
    }

    
    
//    iTunesFileTrack * ift=[HCoreConfig getItunesFiletrackWithPath:songitem.localPath];
//    debugLog(@"lyrics:%@",ift.lyrics);

    
    
//    //检查歌曲是否有内嵌歌词
//    ID3Tag * id3tag=[ID3TagParser parseAudioFileForID3Tag:[NSURL fileURLWithPath:songitem.localPath]];
//    if (id3tag) {
//        debugLog(@"emb lyric:%@",id3tag.lyricist);
//    }
    
    //大于20秒歌曲才加载歌词
    if (songitem.songDuration>20000) {

        //先查询数据库有没有歌词文件record
        NSString * lyricpath=[HSQLManager getLyricPathWithSongItem:songitem];
        
        //如果有歌词文件
        if (lyricpath) {
            
            [self.lyricView.remindLab setHidden:YES];
            [self.lyricView loadDataWithLyricPath:lyricpath withAlert:NO];
            
        }
        
        else {

            //检查本地歌曲是否有内嵌歌词
            
            if(![songitem.localPath isEqualToString:@""]){
            
            TagReader * tagreader=[[TagReader alloc] initWithFileAtPath:songitem.localPath];
            NSString * emLyrics=tagreader.lyrics;
            //debugLog(@"歌词:%@",tagreader.lyrics);

            //如果itunes歌曲有内嵌的歌词
            if (![emLyrics isEqualToString:@""]) {
                
                [[NSFileManager defaultManager] removeItemAtPath:tempLyricPath error:nil];


                [emLyrics writeToFile:tempLyricPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
                
                 [self.lyricView loadDataWithLyricPath:tempLyricPath withAlert:NO];
                
                 [self.lyricView.remindLab setHidden:YES];
                return;
            }
        }
        
            [self.lyricView.remindLab setHidden:NO];
            
            //如果开启歌词下载
            if ([HCoreConfig shareConfig].autoDownloadLyrics) {
                //没有歌词,下载
                [HMainDownloader requestLyricWithSongItem:songitem
                                                   server:GECIMIAPISERVER //BAPIWEBSERVER,GECIMIAPISERVER
                                                 subParam:nil
                                               postStrArr:nil
                                      subTheadfinisHandel:^(BOOL success,NSString * localLrcpath){
                                          
                                          __block   HSongItem * currentSongItem=[HJAudioPlayer sharePlayer].currentPlaySongItem;
                                          
                                          if (success) {
                                              dispatch_async(dispatch_get_main_queue(),^{
                                                  
                                                  //下载完后判断下载的歌词是否匹配当前正在播放的歌曲
                                                  if (currentSongItem) {
                                                      
                                                      if (![currentSongItem.localPath isEqualToString:@""] && [currentSongItem.localPath isEqualToString:songitem.localPath]) {
                                                          
                                                          [self.lyricView loadDataWithLyricPath:localLrcpath withAlert:NO];
                                                          
                                                      } else if (![currentSongItem.urlPath isEqualToString:@""] && [currentSongItem.urlPath isEqualToString:songitem.urlPath]) {
                                                          
                                                          [self.lyricView loadDataWithLyricPath:localLrcpath withAlert:NO];
                                                          
                                                      }
                                                      
                                                      
                                                      
                                                  }
                                                  
                                                  
                                              });
                                              
                                          } else {
                                              
                                              
                                              
                                          }
                                      }];
            }

            
            
            
            
        }
        
        
        
    }
    

}


#pragma mark 设置播放按钮图片
-(void)configThePlayButtonImg{

    
    if ([HJAudioPlayer sharePlayer].currentUsePlayerType==ORGMEngineType) {

        if([HJAudioPlayer sharePlayer].orgmenginePlayer.currentState==ORGMEngineStatePlaying) {
    
        [self.playButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pause_nml"]];
        [self.playButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pause_hlt"]];
    
        } else {
    
        [self.playButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_nml"]];
        [self.playButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_hlt"]];
    
    
          }
        
    } else if ([HJAudioPlayer sharePlayer].currentUsePlayerType==DOUAudioType){
    
    
        if([[HJAudioPlayer sharePlayer].streamPlayerer status]==DOUAudioStreamerPlaying) {
            
            [self.playButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pause_nml"]];
            [self.playButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pause_hlt"]];
            
        } else {
            
            [self.playButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_nml"]];
            [self.playButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_hlt"]];
            
            
        }
    
    }
 
}


#pragma mark 根据上次的播放信息配置ui,播放队列等
-(void)configPlayplaneUI{

//  //volume
//   NSNumber * volumeNumber=[[HCoreConfig shareConfig].currentPlayInfo objectForKey:HVolume];
//    float volume=[volumeNumber floatValue];
//    [self.soundSlider setFloatValue:volume];
//    [HAudioPlayer sharePlayer].volume=volume;
//
//  //playmode
//    NSNumber * playmode=[[HCoreConfig shareConfig].currentPlayInfo objectForKey:HPlayMode];
//    
//
//    

}


#pragma mark --------全局加载/处理 reminder

//loading reminder
-(void)addGLoadingReminderWithTitle:(NSString*)thetitle{


    [self.window.contentView addSubview: self.coverView];
    
    
    [self.loadingReminder starRemindAnimationWithText:thetitle];
    [self.window.contentView addSubview:self.loadingReminder];
    self.rootContentView.disableTouch=YES;
}


-(void)removeGLoadingReminder{

    
    [self.coverView removeFromSuperview];
    
    [self.loadingReminder stopRemindAnimation];
    [self.loadingReminder removeFromSuperview];
    self.rootContentView.disableTouch=NO;
}



//success reminder
-(void)addAutoRemoveSuccessReminderWithTitle:(NSString*)title{

    dispatch_async(dispatch_get_main_queue(),^{
    
    if (title) {
        self.successReminder.remindTf.stringValue=title;
    } else {
        self.successReminder.remindTf.stringValue=NSLocalizedString(@"Done", key);
    }
    
    [self.successReminder.remindTf sizeToFit];
    [self.successReminder.remindTf setFrameOrigin:CGPointMake(45, 10)];
    NSRect currentFrame=self.successReminder.remindTf.frame;
    NSSize viewsize=self.successReminder.frame.size;
    self.successReminder.remindTf.frame=NSMakeRect((viewsize.width-45-currentFrame.size.width)/2+45,(viewsize.height-currentFrame.size.height)/2, currentFrame.size.width, currentFrame.size.height);
    
 [self.successReminder setAlphaValue:1.0];
 [self.window.contentView addSubview:self.successReminder];
    
    
  //N 秒后移除
    self.removeReminderTimer=[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(removeReminder) userInfo:nil repeats:NO];
    });

}



//failed reminder
-(void)addAutoRemoveFailReminderWithTitle:(NSString*)title{
    
    dispatch_async(dispatch_get_main_queue(),^{
    if (title) {
        self.failReminder.remindTf.stringValue=title;

    } else {
        self.failReminder.remindTf.stringValue=NSLocalizedString(@"Done", key);
    }
    
    [self.failReminder.remindTf sizeToFit];
    [self.failReminder.remindTf setFrameOrigin:CGPointMake(45, 10)];
    NSRect currentFrame=self.failReminder.remindTf.frame;
    NSSize viewsize=self.failReminder.frame.size;
    self.failReminder.remindTf.frame=NSMakeRect(45,(viewsize.height-currentFrame.size.height)/2, currentFrame.size.width, currentFrame.size.height);
    
    
    [self.failReminder setAlphaValue:1.0];
    [self.window.contentView addSubview:self.failReminder];
    
    
    //N 秒后移除
    [self.removeReminderTimer invalidate];
    self.removeReminderTimer=[NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(removeReminder) userInfo:nil repeats:NO];
    });
    
}



//移除
-(void)removeReminder{

    [self performSelectorOnMainThread:@selector(mainTheadRemoveReminder) withObject:nil waitUntilDone:YES];

}


//主线程移除
- (void)mainTheadRemoveReminder{

    [NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
        [context setDuration:0.7];
        
        [self.successReminder.animator setAlphaValue:0.0];
        [self.failReminder.animator setAlphaValue:0.0];
        
    } completionHandler:^{
        
        [self.failReminder removeFromSuperview];
        [self.successReminder removeFromSuperview];
    }];
}


#pragma mark  ---------- view layout --------
//
-(void)layoutViewWithFullScreen{
    NSRect windowframe=self.rootContentView.frame;
    

        self.listGroupView.frame=NSMakeRect(0, 0, mainWindowMaxWidth, windowframe.size.height);
        self.playplaneView.frame=NSMakeRect(mainWindowMaxWidth, 0, windowframe.size.width-mainWindowMaxWidth, windowframe.size.height);

    CGFloat planeViewwidth=self.playplaneView.frame.size.width;
    CGFloat planeViewHeigh=self.playplaneView.frame.size.height;
    
    //如果有广告,显示在self.listGroupView下面
    CGFloat genBeginx=140;
    
    //title
    CGFloat titleHeigh=50;
    CGFloat titleWidth=planeViewwidth-genBeginx-20;
    
    //歌词
    CGFloat lyricsBeginx=20;
    CGFloat lyricsBeginy=30;
    CGFloat lyricsWidth=planeViewwidth-lyricsBeginx-self.soundView.frame.size.width;
    CGFloat lyricsHeigh= planeViewHeigh-lyricsBeginy-self.albumArtImgView.frame.size.width-40;
    
    //controlview
    //CGFloat controlWidth=self.playControlView.frame.size.width;
    CGFloat controlbeginX=genBeginx-10;
    
    self.songTitleLab.font=[NSFont systemFontOfSize:25];
    self.songTitleLab.frame=NSMakeRect(genBeginx, planeViewHeigh-titleHeigh-10, titleWidth, titleHeigh);
    self.durationView.frame=NSMakeRect(genBeginx,planeViewHeigh-NSHeight(self.durationView.frame)-50-10,planeViewwidth-genBeginx-50, self.durationView.frame.size.height);
    
    self.playControlView.frame=NSMakeRect(controlbeginX,NSMinY(self.durationView.frame)-self.playControlView.frame.size.height-15, ControlViewFrame.size.width*1.5, ControlViewFrame.size.height*1.5);
    
    self.soundView.frame=NSMakeRect(planeViewwidth-self.soundView.frame.size.width, planeViewHeigh-titleHeigh-self.soundView.frame.size.height-10, self.soundView.frame.size.width,self.soundView.frame.size.height);
    self.lyricView.frame=NSMakeRect(lyricsBeginx, lyricsBeginy, lyricsWidth, lyricsHeigh);
    
    //share  & setting
    [self.fullSettingBtn setHidden:NO];//fullsetting 40x40
     self.shareBtn.frame=NSMakeRect(NSMaxX(self.playControlView.frame)+10, NSMinY(self.playControlView.frame)+10, 30, 30);
    
//    self.shareBtn.frame=NSMakeRect(NSMinX(self.fullSettingBtn.frame)-50, NSMinY(self.fullSettingBtn.frame)+5, 30, 30);

    
    
    //歌词字体
    [self.lyricView reloadlyricStyleAndData];
    
   //菜单
   [self.searchHeaderView setHidden:YES];


    
   
    
    

}


-(void)layoutViewWithoutFullScreen{
     NSRect windowframe=self.rootContentView.frame;
    

        self.listGroupView.frame=NSMakeRect(0, 0, mainWindowMaxWidth, windowframe.size.height-headerViewHeigh-playPlaneHeigh);
    
        self.playplaneView.frame=NSMakeRect(0,windowframe.size.height-playPlaneHeigh,mainWindowMaxWidth, playPlaneHeigh);

    
    self.songTitleLab.font=[NSFont systemFontOfSize:13];
    self.songTitleLab.frame=SongTitleFrame;
    self.durationView.frame=DurationViewFrame;
    self.soundView.frame=SoundViewFrame;
    self.lyricView.frame=LyricsViewFrame;
    self.playControlView.frame=ControlViewFrame;
    
    //share  & setting
    self.shareBtn.frame=ShareBtnFrame;
    [self.fullSettingBtn setHidden:YES];
    
    //歌词字体
    [self.lyricView reloadlyricStyleAndData];
    
    //菜单
    [self.searchHeaderView setHidden:NO];


    
    
}

#pragma mark -------菜单上的响应方法---------
- (IBAction)clickImport:(NSButton *)sender {
    
    //导入到播放列表更新
    NSMenuItem * mitem=[self.importMenu itemWithTag:importPlistTag];
    
    if (self.playListView.plistDataSource.count>0) {
        NSMenu * menu=[[NSMenu alloc] init];
        [mitem setSubmenu:menu];
        
        NSArray * arr=self.playListView.plistDataSource;
        int index=0;
        for (HPlaylistItem * pitem in arr) {
            NSMenuItem * item =[[NSMenuItem alloc] initWithTitle:pitem.name
                                                          action:@selector(importToPitemSelect:) keyEquivalent:@""];
            item.tag=index;
            [menu addItem:item];
            index++;
        }
        [mitem setSubmenu:menu];
        
        //[self.importMenu update];
        
        
    } else {
     NSMenu * menu=[[NSMenu alloc] init];
     NSMenuItem * item =[[NSMenuItem alloc] initWithTitle:@"empty" action:nil keyEquivalent:@""];
        [menu addItem:item];
     [mitem setSubmenu:menu];
     //[self.importMenu update];
    }
    

    
    
    [HCoreConfig setButton:sender menu:self.importMenu offset:NSMakePoint(-5, -7)];
}

- (IBAction)clickSort:(NSButton *)sender {
    
     NSMenuItem * nameitem=[self.sortMenu itemWithTag:sortNameTag];
     NSMenuItem * dateitem=[self.sortMenu itemWithTag:sortDateTag];
    
    //如果是按名称排序
    if ([[HCoreConfig shareConfig].currentSortType isEqualToString:SortByName]) {
        
        dateitem.state=NSOffState;
        nameitem.state=NSOnState ;
        
    } else {
    
        dateitem.state=NSOnState ;
        nameitem.state=NSOffState;
    
    }
    
    
    [HCoreConfig setButton:sender menu:self.sortMenu offset:NSMakePoint(-5, -7)];
    
}

- (IBAction)clickSkin:(NSButton *)sender {
       [HCoreConfig setButton:sender menu:self.skinMenu offset:NSMakePoint(-5, -7)];
}

- (IBAction)clickStore:(NSButton *)sender {
}


- (IBAction)clickSetting:(NSButton *)sender{

    NSMutableArray * wcarr=[HCoreConfig shareConfig].holdWindoControllerArr;
    
    for (NSWindowController * wcc in wcarr) {
        if ([wcc isKindOfClass:[HSettingWC class]]) {
            return;
        }
        
    }
    
    
    CGFloat adjustHeigh=200.0;
    
    //全屏模式
    if (self.window.styleMask & NSFullScreenWindowMask) {
        adjustHeigh=400;
    }
    

     HSettingWC * wc=[[HSettingWC alloc] initWithWindowNibName:@"HSettingWC"];
    
    [self.window addChildWindow:wc.window ordered:NSWindowAbove];
    [wc.window setFrameOrigin:NSMakePoint(CGRectGetMinX(self.window.frame)+(CGRectGetWidth(self.window.frame)-260)/2,CGRectGetMinY(self.window.frame)+adjustHeigh)];
    
    [[HCoreConfig shareConfig].holdWindoControllerArr addObject:wc];
    // [NSApp runModalForWindow:settingWC.window];



}





- (IBAction)clickSearch:(NSButton *)sender{}

#pragma mark 导入------

//itunes
-(void)importToitunes{

    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:YES];
    [panel setCanChooseDirectories:NO];
    [panel setCanChooseFiles:YES];
    [panel setResolvesAliases:YES];
    [panel setAllowedFileTypes:@[@"public.audio"]];
    
//
//    NSString *panelTitle = NSLocalizedString(@"import to itunes",nil);
//    [panel setTitle:panelTitle];
    

    
    [panel setMessage: NSLocalizedString(@"Select music files", nil)];
    
    //功能按钮显示的title
    NSString *promptString =  NSLocalizedString(@"Import", nil);;
    [panel setPrompt:promptString];
    
    HMainWC *  weakSelf = self;
    
    [panel beginSheetModalForWindow:[weakSelf window] completionHandler:^(NSInteger result){
        
        // Hide the open panel.
        [panel orderOut:self];
        
        // If the return code wasn't OK, don't do anything.
        if (result != NSOKButton) {
            return;
        }
        // Get the first URL returned from the Open Panel and set it at the first path component of the control.
        NSArray * arr =[panel URLs];
        
        NSMutableArray * pathsArr=[NSMutableArray arrayWithCapacity:10];
        for (NSURL * url in arr) {
            [pathsArr addObject:url.path];
        }

//        HPlaylistItem * item=[[HPlaylistItem alloc] init];
//        item.syncid=itunesSyncid;
//        
        HPlaylistItem * item=nil;
        
        for (HPlaylistItem * pitem in [HMainWC shareWc].playListView.dataSource) {
            
            if([pitem isKindOfClass:[HPlaylistItem class]]) {
            if ([pitem.syncid isEqualToString:itunesSyncid]) {
                item=pitem;
                break;
            }
            
            }
        }
        
        [weakSelf.songListView insertSongsToPlaylist:item songsPaths:pathsArr];
        
        //如果当前定位是itunes分类的话需要reload数据和UI
        NSInteger selectRow =[[HMainWC shareWc].playListView.tableV selectedRow];
        if (selectRow!=-1) {
            HPlaylistItem * currentpitem=[[HMainWC shareWc].playListView.dataSource objectAtIndex:selectRow];
            [HJAudioPlayer sharePlayer].shouldUpdateQueue=YES;//需要刷新播放列表的话
            
            //如果当前所在的pitem正好与添加的一致,刷新当前歌曲列表
            if ([currentpitem.syncid isEqualToString:itunesSyncid]) {
                
                [[HMainWC shareWc].songListView reloadSonglistWithPlaylistItem:currentpitem];
            }else {
                
                NSUInteger itunesRow=[[HMainWC shareWc].playListView.dataSource indexOfObject:item];
               
                [[HMainWC shareWc].playListView.tableV selectRowIndexes:[NSIndexSet indexSetWithIndex:itunesRow] byExtendingSelection:NO];
                
            }
            
        }
        
        
    }];


}


//as a new playlist
-(void)importAsnewplist{

    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setCanChooseFiles:NO];
    [panel setResolvesAliases:YES];
    //[panel setAllowedFileTypes:@[(id)kUTTypeFolder]];
    
    //
    //    NSString *panelTitle = NSLocalizedString(@"import to itunes",nil);
    //    [panel setTitle:panelTitle];
    
    
    
    [panel setMessage: NSLocalizedString(@"Select music folder", nil)];
    
    //功能按钮显示的title
    NSString *promptString =  NSLocalizedString(@"Import", nil);;
    [panel setPrompt:promptString];
    
    HMainWC *  weakSelf = self;
    
    [panel beginSheetModalForWindow:[weakSelf window] completionHandler:^(NSInteger result){
        
        // Hide the open panel.
        [panel orderOut:self];
        
        // If the return code wasn't OK, don't do anything.
        if (result != NSOKButton) {
            return;
        }
        // Get the first URL returned from the Open Panel and set it at the first path component of the control.
        NSURL * url =[[panel URLs] lastObject];
        
        
        //book mark
//        NSError * bookmarkerror=nil;
//        NSData * data =[url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope
//                                                includingResourceValuesForKeys:nil
//                                                                 relativeToURL:nil
//                                                                         error:&bookmarkerror];
//        
//        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@""];
//        if (bookmarkerror) {
//            debugLog(@"bookmarkerror:%@",bookmarkerror.description);
//        } else {
//            [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"456"];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//            
//        }
        
       // NSString * folder=url.path;
        
        //添加loading
        [[HMainWC shareWc] addGLoadingReminderWithTitle:nil];
        [[HSQLManager shareSqlMg] openSongDB];//打开数据库
        
        int count;
        [[HMainWC shareWc].playListView createPlaylistWithFolderPath:url handelCount:&count];
        [[HSQLManager shareSqlMg] closeSongDB];//打开数据库
        
        //拖完重刷数据
        [[HMainWC shareWc].songListView desselectAllRow];//取消所有选择的行
        
        [[HMainWC shareWc].playListView  reloadDataSource];
        
        
        //导入后刷新定位播放列表,选中时再高亮[会有问题,所以延时刷新
        [[HMainWC shareWc].playListView  performSelector:@selector(locationRowAfterimport) withObject:nil afterDelay:0.1];
        
    }];




}

//import certain playlist
-(void)importToPitemSelect:(NSMenuItem*)item{

    HPlaylistItem * pitem=[HMainWC shareWc].playListView.plistDataSource[item.tag];
    NSUInteger row=item.tag+[HMainWC shareWc].playListView.topGroupArr.count;
    
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:YES];
    [panel setCanChooseDirectories:NO];
    [panel setCanChooseFiles:YES];
    [panel setResolvesAliases:YES];
    [panel setAllowedFileTypes:@[@"public.audio"]];
    
    //
    //    NSString *panelTitle = NSLocalizedString(@"import to itunes",nil);
    //    [panel setTitle:panelTitle];
    
    
    
    [panel setMessage: NSLocalizedString(@"Select music files", nil)];
    
    //功能按钮显示的title
    NSString *promptString =  NSLocalizedString(@"Import", nil);;
    [panel setPrompt:promptString];
    
    HMainWC *  weakSelf = self;
    
    [panel beginSheetModalForWindow:[weakSelf window] completionHandler:^(NSInteger result){
        
        // Hide the open panel.
        [panel orderOut:self];
        
        // If the return code wasn't OK, don't do anything.
        if (result != NSOKButton) {
            return;
        }
        // Get the first URL returned from the Open Panel and set it at the first path component of the control.
        NSArray * urls =[panel URLs];
        
      
        NSMutableArray * arr=[NSMutableArray arrayWithCapacity:10];
        for (NSURL * url in urls) {
            [[HMainWC shareWc].playListView gengrateHsongItemsWithUrl:url filepath:nil holdArr:&arr];
        }
        
        

        [[HSQLManager shareSqlMg] openSongDB];//打开数据库
        
        [HSQLManager batchInsertSongsWithPlaylist:pitem songs:arr db:[HSQLManager shareSqlMg].songDB];
        
        [[HSQLManager shareSqlMg] closeSongDB];//关闭数据库
        

       
        
        NSInteger selectRow =[[HMainWC shareWc].playListView.tableV selectedRow];
        if (selectRow!=-1) {
            HPlaylistItem * currentpitem=[[HMainWC shareWc].playListView.dataSource objectAtIndex:selectRow];
            [HJAudioPlayer sharePlayer].shouldUpdateQueue=YES;//需要刷新播放列表的话
            
            //如果当前所在的pitem正好与添加的一致,刷新当前歌曲列表
            if ([currentpitem isEqualTo:pitem]) {

                [[HMainWC shareWc].songListView reloadSonglistWithPlaylistItem:currentpitem];
            }else {
            
                [[HMainWC shareWc].playListView.tableV selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
            
            }
            
        }
        
        

        
    }];

    


}

#pragma mark 排序------
-(void)sortSelect:(NSMenuItem*)item{

//    
//    debugLog(@"state:%d",item.state);
//
//    NSMenuItem * nameitem=[self.importMenu itemWithTag:sortNameTag];
//    NSMenuItem * dateitem=[self.importMenu itemWithTag:sortDateTag];
    //如果是按名称排序
    if (item.tag==sortNameTag) {
        
        [HCoreConfig shareConfig].currentSortType=SortByName;
        
        
    } else {
        
        [HCoreConfig shareConfig].currentSortType=SortByDate;
        
    }
    
       [[HMainWC shareWc].songListView refreshWhenSortTypeChange];
    
}


#pragma mark skin------
-(void)skinmake{

 [[HSampleSkinDesignerWC shareWc] showWindow:self];

}


-(void)skinSelect:(NSMenuItem*)sender{

    //debugLog(@"tag:%d",sender.tag);
    
    
    if (sender.state==NSOnState) {
        return;
    }
    
    
    NSArray * items= [self.skinMenu itemArray];

    for (NSMenuItem * item in items) {
        [item setState:NSOffState];
    }
    sender.state=NSOnState;
    
    
    
    NSDictionary * skininfoDic=self.skinList[sender.tag];
    NSString * skinname=skininfoDic[@"skinName"];
    NSString * sourcepath=fileBundlePath(skinname, @"plist");

    NSFileManager *filemanager=[NSFileManager defaultManager];
    [filemanager removeItemAtPath:skinConfigPath error:nil];
    [filemanager copyItemAtPath:sourcepath toPath:skinConfigPath error:nil];


    [[HCoreConfig shareConfig].currentSkinManager reloadWithConfigPath:skinConfigPath];
    
    [self refreshSkin];
    [self.grwindow makeKeyAndOrderFront:self];


}


#pragma mark 设置播放模式ui------
-(void)configPlayModeImage{

    NSUInteger mode=[HJAudioPlayer sharePlayer].currentPlayMode;
    // 1 :顺序  2:循环  3:随机 4.单曲循环
    switch (mode) {
        case 1:
             [self.playModeButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_mode_list_nml"]];
            break;
        case 2:
            [self.playModeButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_mode_cycle_nml"]];
            break;
        case 3:
            [self.playModeButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_mode_random_nml"]];
            break;
        case 4:
            [self.playModeButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_mode_single_nml"]];
            break;
            
        default:
            break;
    }
    



}


#pragma mark  ---------- window delegate --------
- (BOOL)windowShouldClose:(id)sender{
    
    
    

    return YES;
    
}



- (void)windowWillClose:(NSNotification *)notification{
    //[[NSApplication sharedApplication] terminate:nil];
    
    //保存设置
//    [self saveLastplayInfoSetting];

    [NSApp terminate:self];
    
}



- (void)windowWillEnterFullScreen:(NSNotification *)notification  {

    [self.window setMaxSize:NSMakeSize(10000, 10000)];
    
    //进入全屏前,歌词页面要归位
    NSDrawerState state = [self.lyricDrawer state];
    if (NSDrawerOpeningState == state || NSDrawerOpenState == state) {
        [self.lyricDrawer  close];
    }

}


- (void)windowDidEnterFullScreen:(NSNotification *)notification{
    //debugLog(@"enter:%@",NSStringFromRect(self.rootContentView.frame));
 [self layoutViewWithFullScreen];

}


- (void)windowWillExitFullScreen:(NSNotification *)notification{
 [self.window setMaxSize:NSMakeSize(mainWindowMaxWidth, 10000)];
    
  
 
}


- (void)windowDidExitFullScreen:(NSNotification *)notification{
  //debugLog(@"exit:%@",NSStringFromRect(self.rootContentView.frame));
    [self layoutViewWithoutFullScreen];
    
}

#pragma mark ------for dou streamer delegate----------
//用于streamEr处理下一首歌曲
-(void)handleNextSongForStreamerPlayer{

    
    //先关闭当前歌曲的boomakr
    [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
    
    if ([HJAudioPlayer sharePlayer].currentUsePlayerType==DOUAudioType) {

        HSongItem * songitem=[[HJAudioPlayer sharePlayer] theNextSongItem];
    
        if (!songitem) {
            [[HJAudioPlayer sharePlayer] stopAction];
            return;
        }
        
        //先播放,打开了bookmark后才能读取图片等信息
            [[HJAudioPlayer sharePlayer] playSongWithSongItem:songitem];
            [self resetUIWithSongItemChange:songitem];
        

        

    }

}

#pragma mark ------audio engine delegate----------

- (NSURL *)engineExpectsNextUrl:(ORGMEngine *)engine {
   
    
    //先关闭当前歌曲的boomakr
    [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
    
    HSongItem * songitem=[[HJAudioPlayer sharePlayer] theNextSongItem];
    
    if (!songitem) {
        [[HJAudioPlayer sharePlayer] stopAction];
        return nil;
    }
    
    //如果不是无损,切换到streamer
    if ([HCoreConfig checkLosslessWithSongItem:songitem]==NO) {
        [[HJAudioPlayer sharePlayer] stopAction];
        
        [[HJAudioPlayer sharePlayer] playSongWithSongItem:songitem];
        [self resetUIWithSongItemChange:songitem];
        
        
        
        return nil;
    }
    
    
    [[HJAudioPlayer sharePlayer] openBookmarWithCurrentItem];
     NSURL* url = [NSURL fileURLWithPath:songitem.localPath];
    [self resetUIWithSongItemChange:songitem];
    
   

    return url;
}

- (void)engine:(id)engine didChangeState:(NSInteger)state {
    switch (state) {
            
            //stop 按钮按下
        case ORGMEngineStateStopped: {
            debugLog(@"Stopped");
            //先关闭当前歌曲的boomakr
            [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
            
            //时间清0
            [[HJAudioPlayer sharePlayer] seekToTimeWithFloatValue:0.0f];
            self.currentDurationLab.stringValue=@"0:00";
            [self.durationSlider setFloatValue:0.0];
            
            //播放按钮
            [self.playButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_nml"]];
            [self.playButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_hlt"]];
            
            break;
        }
            //
        case ORGMEngineStatePaused: {
            
            [self.playButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_nml"]];
            [self.playButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_play_hlt"]];
            
            //debugLog(@"pause");
            break;
        }
        case ORGMEngineStatePlaying: {
           // debugLog(@"Playing");
            //ormiga音频引擎有bug,需要播放过歌曲后才能正常
           // [[HJAudioPlayer sharePlayer] setVolumeWithFloatValue:self.soundSlider.floatValue];
            
            //更改封面
            //更改title
            //duradion
            
            [self.playButton setImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pause_nml"]];
            [self.playButton setAlternateImage:[[HCoreConfig shareConfig] getImageWithMainBundle:@"icon_pause_hlt"]];
            
            
            
        }
        case ORGMEngineStateError:
            if ([engine isKindOfClass:[ORGMEngine class]]) {
              debugLog(@"ORGMEngineStateError error:%@",[[HJAudioPlayer sharePlayer].orgmenginePlayer.currentError localizedDescription]);
            } else {
            debugLog(@"streamer error:%@",[[HJAudioPlayer sharePlayer].streamPlayerer.error localizedDescription]);
            }
            
          
            break;
    }
}


#pragma mark -----------playplane---------

- (IBAction)likeBtnClick:(NSButton *)sender {

    //如果当前播放的曲目,需要更新object,播放面板
    HSongItem * songitem=[HJAudioPlayer sharePlayer].currentPlaySongItem;
    if(songitem){
        
        if (sender.state==NSOnState) {
            songitem.islike=YES;
        }
        //unlike
        else {
            songitem.islike=NO;
            
        }
        
        
        
        //属于itunes歌曲
        if([HCoreConfig checkSongisBelongToItunesWithPath:songitem.localPath]){
            //itunes和数据库都要同步
            [HCoreConfig likeItunesSongWithSongitem:songitem];
            [HSQLManager updateLikeStateWithItem:songitem];//同样更改数据库同步
            
        }else {
            
            [HSQLManager updateLikeStateWithItem:songitem];//更改数据库同步
            
        }
        
        
        //刷新当前列表
        HPlaylistItem * pitem=[self.playListView getCurrentSelectPlaylistItem];
        
        if ([pitem.syncid isEqualToString:songitem.playListSyncID]) {
            [self.songListView reloadSonglistWithPlaylistItem:pitem];
        }
        
        
        
        
    } else {
    
        sender.state=NSOffState;
    
    }
    
    
    
}

- (IBAction)playModeClick:(NSButton *)sender {
    
   //初始化为顺序播放 // 1 :顺序  2:循环  3:随机 4.单曲循环
    if([HJAudioPlayer sharePlayer].currentPlayMode==4) {
        [HJAudioPlayer sharePlayer].currentPlayMode=1;
    } else {
        [HJAudioPlayer sharePlayer].currentPlayMode++;
    }
    
    [[HJAudioPlayer sharePlayer].hadPlayRandomDic removeAllObjects];//清空随机字典表
    
    [self configPlayModeImage];
    
}

- (IBAction)nextBtnClick:(NSButton *)sender {
   
    
    //先关闭当前歌曲的boomakr
    [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
    
 HSongItem * item = [[HJAudioPlayer sharePlayer] getNextSongItemWithActionIsNext:YES];
    
    if(item) {

        [[HJAudioPlayer sharePlayer] playSongWithSongItem:item];
        
        [[HMainWC shareWc] resetPlayplaneUIWithSongItem:item];
        
        HPlaylistItem * pitem=[[HMainWC shareWc].playListView getCurrentSelectPlaylistItem];
        //如果当前播放的列表定位 与选中的一致,刷新列表
        if ([pitem.syncid isEqualToString:item.playListSyncID]) {
            [self.songListView.tableV reloadData];
        }
        
        
        
    }
    
    
}

- (IBAction)prevBtnClick:(NSButton *)sender {
    
    //先关闭当前歌曲的boomakr
    [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
    
   HSongItem * item = [[HJAudioPlayer sharePlayer] getNextSongItemWithActionIsNext:NO];
    
    if(item) {
        
        [[HJAudioPlayer sharePlayer] playSongWithSongItem:item];
        
        [[HMainWC shareWc] resetPlayplaneUIWithSongItem:item];
        
        HPlaylistItem * pitem=[[HMainWC shareWc].playListView getCurrentSelectPlaylistItem];
        //如果当前播放的列表定位 与选中的一致,刷新列表
        if ([pitem.syncid isEqualToString:item.playListSyncID]) {
            [self.songListView.tableV reloadData];
        }
        
        
    }
    
    
    
}


- (IBAction)playBtnClick:(NSButton *)sender {
    

    
    if ([HJAudioPlayer sharePlayer].currentUsePlayerType==ORGMEngineType) {
    
        ORGMEngineState  ostate=[HJAudioPlayer sharePlayer].orgmenginePlayer.currentState;
        ORGMEngine * enginePlayer=[HJAudioPlayer sharePlayer].orgmenginePlayer;
       
        if(ostate==ORGMEngineStatePlaying) {
            
            [enginePlayer pause];
            
        } else if(ostate==ORGMEngineStatePaused){
            [[HJAudioPlayer sharePlayer] openBookmarWithCurrentItem];
            [enginePlayer resume];
            
        }else if(ostate==ORGMEngineStateStopped){
            
            HSongItem * si=[HJAudioPlayer sharePlayer].currentPlaySongItem;
            if(si){
                
                [[HJAudioPlayer sharePlayer] playSongWithSongItem:si];
                
            }
            
        }

        
    } else if([HJAudioPlayer sharePlayer].currentUsePlayerType==DOUAudioType) {
    
        NSUInteger  streamStatus=[[HJAudioPlayer sharePlayer].streamPlayerer status];
        DOUAudioStreamer * sreamer=[HJAudioPlayer sharePlayer].streamPlayerer;
        
        if (streamStatus==DOUAudioStreamerPaused) {
            [[HJAudioPlayer sharePlayer] openBookmarWithCurrentItem];
            [sreamer play];
        } else if (streamStatus==DOUAudioStreamerPlaying) {
          [sreamer pause];
        } else {
            HSongItem * si=[HJAudioPlayer sharePlayer].currentPlaySongItem;
            if(si){
                [[HJAudioPlayer sharePlayer] playSongWithSongItem:si];
            }

        }

    }
    
 
    
}



- (IBAction)shareBtnClick:(NSButton *)sender {

    NSMutableArray *shareItems = [NSMutableArray arrayWithCapacity:2];
    //截图
    NSImage *image = [HCoreConfig windowImageShot:self.window];
    
    NSString * des=@"";
    
    HSongItem * si=[HJAudioPlayer sharePlayer].currentPlaySongItem;
    if(si) {
        NSString * info=[NSString stringWithFormat:@"%@-%@",si.songName,si.artist];
        des=[NSString stringWithFormat:NSLocalizedString(@"ShareDESWithSong", nil),info];
        
    
    } else {
        des=NSLocalizedString(@"ShareDESWithOutSong",nil);
    }
    
    des=[des stringByAppendingString:@"  https://itunes.apple.com/us/app/gladmusic/id939621912"];
    
    [shareItems addObject:des];
    

    
    
    //截图使用
//    NSData * dat=[HCoreConfig imageConvertData:image imageFileType:NSPNGFileType fitDeviceScale:NO];
//    [dat writeToFile:[HDocumentDirectory stringByAppendingPathComponent:@"test.png"] atomically:YES];
    if (image) {
        [shareItems addObject:image];
    }
    

    NSSharingServicePicker *sharingServicePicker = [[NSSharingServicePicker alloc] initWithItems:shareItems];
    sharingServicePicker.delegate = self;
    [sharingServicePicker showRelativeToRect:[self.shareBtn bounds] ofView:self.shareBtn preferredEdge:(NSMinYEdge | NSMinXEdge)];

    
    
}

- (IBAction)showFullSetting:(NSButton *)sender {
    
    [self clickSetting:nil];
}

- (IBAction)soundChange:(HMusicSlider *)sender {
    
    float sound=[sender floatValue];
    //debugLog(@"sound:%f",sound);
    //设置音量
    [[HJAudioPlayer sharePlayer] setVolumeWithFloatValue:sound];
    
}

- (IBAction)durationChange:(HMusicSlider *)sender {
  
    [[HJAudioPlayer sharePlayer] seekToTimeWithFloatValue:sender.floatValue];
  
    
}


- (IBAction)addSound:(id)sender {
    
    NSNumber * volume=[HJAudioPlayer sharePlayer].volume;
    
    float thenewVolume=volume.floatValue+0.1;
    thenewVolume=(thenewVolume>1.0?1.0:thenewVolume);
    
    //设置音量UI
    [[HJAudioPlayer sharePlayer] setVolumeWithFloatValue:thenewVolume];
    [self.soundSlider setFloatValue:thenewVolume];
}


- (IBAction)minuteSound:(id)sender {
    
    NSNumber * volume=[HJAudioPlayer sharePlayer].volume;
    
    float thenewVolume=volume.floatValue-0.1;
    thenewVolume=(thenewVolume<0.0?0.0f:thenewVolume);
    
    //设置音量UI
    [[HJAudioPlayer sharePlayer] setVolumeWithFloatValue:thenewVolume];
    [self.soundSlider setFloatValue:thenewVolume];
    
}

#pragma mark - Sharing service picker delegate methods

- (NSArray *)sharingServicePicker:(NSSharingServicePicker *)sharingServicePicker sharingServicesForItems:(NSArray *)items proposedSharingServices:(NSArray *)proposedServices
{
    /*
     If you're only interested in providing your own services, you could ignore the array of proposed services and construct and return your own array. Alternatively, as shown here, you add your service to the list of those offered by the system.
     */
    
    NSArray *services = proposedServices;
    
    return services;
}


- (id <NSSharingServiceDelegate>)sharingServicePicker:(NSSharingServicePicker *)sharingServicePicker delegateForSharingService:(NSSharingService *)sharingService
{
    /*
     Implementing this method sets the delegate for the sharing service picker created in chooseSharingService:.
     In this example, it's for illustration only -- the delegate method simply logs which service was chosen. In your application, you might want to use the delegate method for something more useful, like managing resources.
     */
    return self;
}


- (void)sharingServicePicker:(NSSharingServicePicker *)sharingServicePicker didChooseSharingService:(NSSharingService *)service
{
    NSLog(@"Picked this service: %@", service);
}


#pragma mark - Sharing service delegate methods

- (NSRect)sharingService:(NSSharingService *)sharingService sourceFrameOnScreenForShareItem:(id<NSPasteboardWriting>)item
{
    
    
//    if ([item isKindOfClass:[NSImage class]]) {
//        
////        NSImageView *imageView = self.imageView;
////        NSRect imageViewBounds = [imageView bounds];
////        NSSize imageSize = [[imageView image] size];
////        NSRect imageFrame = NSMakeRect((NSWidth(imageViewBounds) - imageSize.width) / 2.0, (NSHeight(imageViewBounds) - imageSize.height) / 2.0, imageSize.width, imageSize.height);
////        NSRect frame = [imageView convertRect:imageFrame toView:nil];
////        frame.origin = [[imageView window] convertBaseToScreen:frame.origin];
////        return frame;
//    }
//    else {
//        return NSZeroRect;
//    }
    
    return NSZeroRect;
}

- (NSImage *)sharingService:(NSSharingService *)sharingService transitionImageForShareItem:(id<NSPasteboardWriting>)item contentRect:(NSRect *)contentRect
{
    if ([item isKindOfClass:[NSImage class]]) {

        return (NSImage*)item;
 
    }
    else {
        return nil;
    }
}


- (NSWindow *)sharingService:(NSSharingService *)sharingService sourceWindowForShareItems:(NSArray *)items sharingContentScope:(NSSharingContentScope *)sharingContentScope
{
    /*
     The window for all the services is self's window.
     The other methods are useful if you share an item which already has a representation in the window, typically an image. You give its frame and the sharing service animates from it.
     */
    return self.window;
}


- (void)sharingService:(NSSharingService *)sharingService didShareItems:(NSArray *)items{

//成功分享 可以获得一款皮肤

}


//#pragma mark - Text view delegate
//
//- (NSSharingServicePicker *)textView:(NSTextView *)textView willShowSharingServicePicker:(NSSharingServicePicker *)servicePicker forItems:(NSArray *)items
//{
//    /*
//     Here you could modify the service picker for the given items.
//     */
//    NSLog(@"Text view using %@ with items: %@", servicePicker, items);
//    
//    return servicePicker;
//}

#pragma mark ------- nsdrawer delegate-------
- (void)drawerWillOpen:(NSNotification *)notification{

   // debugLog(@"will open");
    
    [self.lyricDrawer setContentView:self.lyricView];
}

- (void)drawerDidOpen:(NSNotification *)notification{


    //self.lyricView.frame=CGRectMake(0, 0, self.lyricDrawer.contentSize.width, self.lyricDrawer.contentSize.height);

}



- (void)drawerWillClose:(NSNotification *)notification{
 //debugLog(@"will close");
}
- (void)drawerDidClose:(NSNotification *)notification{

    self.lyricView.frame=LyricsViewFrame;
    [self.playplaneView addSubview:self.lyricView];


}



@end
